#include "ana.h"
#include "ui_ana.h"


Ana::Ana(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Ana)
{


    fileModel = nullptr;
    //ui->menubar->setNativeMenuBar(false);
    flag = 0;
    ui->setupUi(this);
    ui->stackedWidget->setCurrentIndex(0); //默认是主界面
    setFixedSize(800,600);
    init();
    initTree();
    ui->treeView_nowProject->setEditTriggers(nullptr);
    ui->treeView_projectList->setEditTriggers(nullptr);//设置不可编辑，不然也不好处理
    ui->treeView_nowProject->expandAll();
    ui->treeView_projectList->expandAll();//默认展开
    connect(ui->actionAuthor,SIGNAL(triggered()),this,SLOT(show_author()));
    connect(ui->actionOpenProject,SIGNAL(triggered()),this,SLOT(on_pushButton_changeProj_clicked()));
    connect(ui->actionFileSolve,SIGNAL(triggered()),this,SLOT(on_FileSlov_clicked()));
    connect(ui->actionPostSolve,SIGNAL(triggered()),this,SLOT(on_PostSlov_clicked()));
}

Ana::~Ana()
{
    delete ui;
}

void Ana::show_author()
{
    QMessageBox::about(nullptr,"关于","作者：吉法师\nQQ：765715928");
}

//判断项目文件是否存在 不存在则需要创建
void Ana::init()
{

    QFileInfo fileInfo(myfilename);
    //QFile file("E:\\AnaFich\\project.json");
    QFile file(myfilename);
    if(fileInfo.isFile()==true) //存在该文件
    {
        //读文件
        qDebug()<<"文件已存在";
//        file.open(QIODevice::ReadWrite);
//        QByteArray allData = file.readAll();
//        QString result = readJsonfile2string(filename);
        file.close();
    }
    else
    {
        qDebug()<<"文件不存在";
        //生成文件
        if(file.open(QIODevice::ReadWrite))
        {
            qDebug()<<"file open error";
        }
        file.resize(0);
        file.close();

    }


}

void Ana::init_temp()
{
    QJsonObject root = readJsonfile2Object(myfilename);
    tempobjectproject = root;




}

void Ana::on_exit_clicked()
{
    close();
}

void Ana::on_add_clicked()
{
    ui->lineEdit_proj->setText("");
    ui->lineEdit_descrioption->setText("");
    ui->stackedWidget->setCurrentIndex(1);
    setFixedSize(800,200);

}


void Ana::on_pushButton_return_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
    setFixedSize(800,600);
}



void Ana::on_pushButton_save_clicked()
{
    if(ui->lineEdit_proj->text()==nullptr)
    {
           QMessageBox::warning(nullptr,"警告","项目名称不能为空");
           //setFixedSize(800,600);
    }
    else
    {
        //输入了项目名称
        QString projectname = ui->lineEdit_proj->text();
        QString desc = ui->lineEdit_descrioption->text();
        QFile file(myfilename);
        file.open(QIODevice::ReadOnly); //打开文件

        QByteArray all = file.readAll();
        file.close();
        QJsonParseError json_error;
        QJsonDocument jsonDoc(QJsonDocument::fromJson(all,&json_error)); //读取json
//        if(json_error.error!=QJsonParseError::NoError)
//        {
//            qDebug()<<"项目文件读取失败"<<__LINE__;
//        }
        QJsonObject rootObj = jsonDoc.object();


        if(rootObj.contains("project")) //如果这个json文件有"project"键
        {
            QJsonValue subarray = rootObj.value("project");
            qDebug()<<"array = "<<subarray;
            QJsonArray array = subarray.toArray();

            if(JsonArrayContain(array,"name",projectname)==true)
            {
                QMessageBox::warning(nullptr,"警告","项目名称重复");
            }
            else
            {
                qDebug()<<array;
                qDebug()<<"项目名称唯一";
                QJsonObject newProject;
                newProject.insert("name",projectname);
                newProject.insert("description",desc);
                QJsonArray filearray;
                newProject.insert("file",filearray);


                array.append(newProject);
                rootObj.insert("project",array);

                QJsonDocument jsonfile(rootObj);
                qDebug()<<"jsonfile = "<<jsonfile;
                file.open(QIODevice::WriteOnly);

                file.write(jsonfile.toJson());
                file.close();
            }



        }
        else
        {
            //写入json;

            QJsonArray projectArray;

            QJsonObject projectinfo ;
            projectinfo.insert("name",projectname);
            projectinfo.insert("description",desc);
            projectArray.insert(0,projectinfo);
            rootObj.insert("project",projectArray);
            file.open(QIODevice::WriteOnly);
            QJsonDocument jsonfile(rootObj);
            qDebug()<<"jsonfile = "<<jsonfile;
            file.write(jsonfile.toJson());
            file.close();


        }
        ui->stackedWidget->setCurrentIndex(0);
        initTree();
        setFixedSize(800,600);

    }
}

//读取json文件，将其转为json字符串
QString Ana::readJsonfile2string(QString filename)
{
    QFile file(filename);
    file.open(QIODevice::ReadWrite); //打开文件

    QByteArray all = file.readAll();
    file.close();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(all,&json_error)); //读取json
    QJsonObject rootObj = jsonDoc.object();
    QString result = QString(QJsonDocument(rootObj).toJson());
    file.close();
    return result;
}

//读Json文件返回Json对象
QJsonObject Ana::readJsonfile2Object(QString filename)
{
    QFile file(filename);
    file.open(QIODevice::ReadWrite); //打开文件

    QByteArray all = file.readAll();
    file.close();
    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(all,&json_error)); //读取json
    QJsonObject rootObj = jsonDoc.object();
    return rootObj;
}

//Json对象转为QString
QString Ana::Json2QString(QJsonObject json)
{
    QString result = QString(QJsonDocument(json).toJson());
    return result;
}

bool Ana::JsonArrayContain(QJsonArray array, QString jsonObject, QString target)
{
    //传入了array ，jsonobject为要找到的json对象键名，target为这个对象的值
    for(int i = 0;i<array.size();i++)
    {
        QJsonValue arrayValue = array.at(i);
        QString projectname = arrayValue[jsonObject].toString();
        qDebug()<<projectname<<" "<<__LINE__;
        if(projectname == target)
        {
            qDebug()<<"识别到";
            return true;
        }
    }
    return false;
}

void Ana::on_main_delete_clicked()
{
    //点击后删除该项目或者内容
    QModelIndex selected  = ui->treeView_projectList->currentIndex(); //选中的行
    selected = selected.sibling(selected.row(),0);
    QString index = ui->treeView_projectList->model()->itemData(selected).values()[0].toString();

    qDebug()<<index<<__LINE__;
    if(selected.parent().isValid()==false) //选中了项目名
    {
        QMessageBox::StandardButton result = QMessageBox::information(nullptr,"提示","确定要删除项目"+index+"吗？",QMessageBox::Yes|QMessageBox::No);
        if(result == QMessageBox::Yes)
        {
            //这个时候获得了选中的项目的字符串
            QJsonObject rootObj = readJsonfile2Object(myfilename);
            QJsonArray rootArray = readJsonObjectReturnArray(rootObj,"project");
            for(int i=0;i<rootArray.size();i++)
            {
                QJsonValue rootValue = rootArray.at(i);
                if(rootValue["name"].toString()==index)
                {
                    rootArray.removeAt(i);
                }
            }
            rootObj = {
                         {"project",rootArray}
                       };
            QJsonDocument jsonfile(rootObj);
            QFile file(myfilename);
            file.open(QIODevice::WriteOnly);

            file.write(jsonfile.toJson());

            file.close();
            initTree();
        }
    }
    else
    {
        //选中了配置名
        QMessageBox::StandardButton result = QMessageBox::information(nullptr,"提示","确定要删除配置"+index+"吗？",QMessageBox::Yes|QMessageBox::No);
        if(result == QMessageBox::Yes)
        {
            QJsonObject rootObj = readJsonfile2Object(myfilename);
            QJsonArray rootArray = readJsonObjectReturnArray(rootObj,"project");
            QString parent = selected.parent().data().toString();
            QJsonArray fileArray;
            QString filename;
            int rootindex = 0,fileindex = 0;
            for(int i=0;i<rootArray.size();i++)
            {
                QJsonValue value = rootArray.at(i);
                if(value["name"].toString() == parent)
                {
                    fileArray = value["file"].toArray();
                    rootindex = i;
                    break;
                }
            }
            for(int i=0;i<fileArray.size();i++)
            {
                QJsonValue temp = fileArray.at(i);
                if(temp["filename"].toString() == index)
                {
                    fileArray.removeAt(i);
                    fileindex = i;

                    break;//实现删除 现在要组Json写文件了
                }
            }
            QJsonObject root{
                {"name",parent},
                {"file",fileArray}
            };
            rootArray[rootindex] = root; //将Json转回去



            rootObj = {
                {"project",rootArray}
            };
            QJsonDocument jsonfile(rootObj);
            QFile file(myfilename);
            file.open(QIODevice::WriteOnly);

            file.write(jsonfile.toJson());

            file.close();
            initTree();

        }
    }

}

void Ana::initTree()
{
    QStandardItemModel * model = new QStandardItemModel(ui->treeView_projectList);
    model->setHorizontalHeaderLabels(QStringList()<<QStringLiteral("项目名称")<<QStringLiteral("描述"));

    QJsonObject rootjson = readJsonfile2Object(myfilename);
    QJsonArray array = readJsonObjectReturnArray(rootjson,"project");
    ui->comboBox_project->clear();
    ui->comboBox_project->addItem("无");
    for(int i=0;i<array.size();i++)
    {
        QJsonValue value = array.at(i);
        QString project = value["name"].toString();

        QString desc = value["description"].toString();
        QList<QStandardItem *> items1;
        QStandardItem * item1 = new QStandardItem(project);
        QStandardItem * item2 = new QStandardItem(desc);
        items1.append(item1);
        items1.append(item2);
        model->appendRow(items1);
        ui->comboBox_project->addItem(project);
        QJsonArray filearray = value["file"].toArray();

        for(int j=0;j<filearray.size();j++)
        {
            //二级节点
            QJsonValue valuefile = filearray.at(j);
            QString filename = valuefile["filename"].toString();
            QList<QStandardItem *> items2;
            QStandardItem * item3 = new QStandardItem(filename);
            items2.append(item3);
            item1->appendRow(items2);
        }
    }
    ui->treeView_projectList->setModel(model);


}

QJsonArray Ana::readJsonObjectReturnArray(QJsonObject object, QString jsonkey)
{
    QJsonValue value = object.value(jsonkey);
    QJsonArray array = value.toArray();
    return array;
}


void Ana::on_pushButton_changeProj_clicked()
{
    if(ui->comboBox_project->currentText()=="无")
    {
        QMessageBox::warning(nullptr,"警告","请选择正确的项目或者先创建项目");
    }
    else
    {
        ui->stackedWidget->setCurrentIndex(2);
        QString projectname = ui->comboBox_project->currentText();
        ui->label_current_project->setText(projectname);
        QJsonObject rootObject = readJsonfile2Object(myfilename);

        //获得json下的project
        QJsonArray array = readJsonObjectReturnArray(rootObject,"project");


        initTree_file(projectname,array); //初始化该项目的treeview
        ui->tableView_nowfile->clearSpans();
    }

}

void Ana::on_pushButton_file_return_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
    initTree();
}

void Ana::on_pushButton_addProject_file_clicked()
{
    QString newfilename = ui->lineEdit_projectfile->text();
    if(newfilename == "")
    {
        QMessageBox::warning(nullptr,"警告","请输入要添加的配置文件名");
        return;
    }
    QJsonObject rootObject = readJsonfile2Object(myfilename);
    int index = 0;

    //获得json下的project
    QJsonArray array = readJsonObjectReturnArray(rootObject,"project");
    QJsonObject file; //项目的主Json
    QJsonArray file_setup; //项目的文件配置
    for(int i=0;i<array.size();i++)
    {
        QJsonValue value = array.at(i);
        QString projectname = value["name"].toString();
        if(projectname == ui->label_current_project->text())
        {
            file = value.toObject(); //再把这个value转为jsonObject
            index = i;

            break; //结束后续的循环
        }


    }

    QJsonArray filearray = file.find("file")->toArray();
    for(int i=0;i<filearray.size();i++)
    {
        QJsonValue valuethis = filearray.at(i);
        if(valuethis["filename"].toString()==newfilename)
        {
            QMessageBox::warning(nullptr,"警告","输入的项目配置重复");
            return;
        }
    }

    QJsonObject toadd{
        {"filename",newfilename}
    };
    QJsonArray newfiledetail;
    toadd.insert("detail",newfiledetail);
    filearray.append(toadd);
    file["file"] = filearray;
    array[index] = file;
    rootObject["project"] = array;

    QFile jsonfile(myfilename);

    if(!jsonfile.open(QIODevice::WriteOnly))
    {
        return;
    }
    QJsonDocument jsondocu(rootObject);
    jsonfile.write(jsondocu.toJson());
    jsonfile.close();
    initTree_file(ui->label_current_project->text(),array);
    ui->lineEdit_projectfile->clear();



}


void Ana::initTree_file(QString project,QJsonArray thisProject)
{
    ui->treeView_nowProject->setModel(nullptr);

    QJsonObject file; //项目的主Json
    QJsonArray file_setup; //项目的文件配置
    for(int i=0;i<thisProject.size();i++)
    {
        QJsonValue value = thisProject.at(i);
        QString projectname = value["name"].toString();
        if(projectname == project)
        {
            file = value.toObject(); //再把这个value转为jsonObject
            break; //结束后续的循环
        }

    }
    if(file.contains("file")==true)
    {
        file_setup = readJsonObjectReturnArray(file,"file");
        //为0也没必要添加了
        if(file_setup.size()!=0)
        {
            QStandardItemModel * model = new QStandardItemModel(ui->treeView_nowProject);
            model->setHorizontalHeaderLabels(QStringList()<<QStringLiteral("配置列表"));
            for(int i=0;i<file_setup.size();i++)
            {
                QJsonValue value = file_setup.at(i);
                QList<QStandardItem*> items1;
                QString filename = value["filename"].toString();
                QStandardItem * item1 = new QStandardItem(filename);
                items1.append(item1);
                model->appendRow(items1);
            }
            ui->treeView_nowProject->setModel(model);
        }
    }

}



void Ana::on_treeView_projectList_clicked(const QModelIndex &index)
{
    //选择的内容有两种，一种是项目名，一种是项目配置名
    //选择的不是项目配置，就不显示
    ui->tableWidget->clearContents(); //先清空 初始化
    ui->tableWidget->setRowCount(0);
    name.clear();
    length.clear();
    types.clear();
    desc.clear();
    //初始化完毕

    QString selectedText = ui->treeView_projectList->model()->itemData(index).values()[0].toString();
    const QModelIndex currindex = ui->treeView_projectList->currentIndex();
    if(currindex.parent().isValid()==false)
    {
        flag = 0;
        //同时将QComboBox的内容切换到点击的值
        for(int i=0;i<ui->comboBox_project->count();i++)
        {
            if(selectedText == ui->comboBox_project->itemText(i))
            {
                ui->comboBox_project->setCurrentIndex(i);
            }
        }
        return;
    }
    else
    {
        QString parent = currindex.parent().data().toString(); //选中的项目名
        qDebug()<<parent<<__LINE__;
        QJsonObject rootObject = readJsonfile2Object(myfilename);
        QJsonArray rootArray = readJsonObjectReturnArray(rootObject,"project");
        QJsonArray fileArray;
        QJsonArray projectArray;
        for(int i=0;i<rootArray.size();i++)
        {
            QJsonValue valueRoot = rootArray.at(i);
            if(valueRoot["name"].toString() == parent)
            {
                projectArray = valueRoot["file"].toArray();

                break;
            }

        }
        QJsonArray detailArray;
        for(int i=0;i<projectArray.size();i++)
        {
            QJsonValue detail = projectArray.at(i);
            if(detail["filename"].toString() == selectedText)
            {
                detailArray = detail["detail"].toArray();

                break;
            }
        }
        //现在取到了文件配置了
        QStringList tableHeader;
        if(detailArray.size() == 0)
        {
            flag = 0;
        }
        else
        {
            flag = 1;
        }
        for(int i=0;i<detailArray.size();i++)
        {
            QJsonValue tableColoum = detailArray.at(i);
            QString Coloum = tableColoum["name"].toString();
            QString len = tableColoum["length"].toString();

            //方便解析的时候直接调用
            name<<tableColoum["name"].toString();
            length<<tableColoum["length"].toString();
            types<<tableColoum["type"].toString();
            desc<<tableColoum["description"].toString();
            tableHeader<<Coloum+"  "+len;

        }
        qDebug()<<tableHeader<<__LINE__;
        ui->tableWidget->setColumnCount(tableHeader.length());
        ui->tableWidget->setHorizontalHeaderLabels(tableHeader);

    }


}

void Ana::on_treeView_nowProject_clicked(const QModelIndex &index)
{
    QString selectedText = ui->treeView_nowProject->model()->itemData(index).values()[0].toString();
    nowfilename = selectedText;
    init_tableview_nowfile(selectedText);
}

// nowfile是当前点击选中的项目内的文件名
void Ana::init_tableview_nowfile(QString nowfile)
{
    ui->tableView_nowfile->clearSpans();
    QJsonObject rootObject = readJsonfile2Object(myfilename);
    QJsonArray projectArray = readJsonObjectReturnArray(rootObject,"project");

    QJsonArray fileArray;
    QJsonArray detail;

    for(int i=0;i<projectArray.size();i++)
    {
        QJsonValue valueproject = projectArray.at(i);
        if(valueproject["name"].toString() == ui->label_current_project->text())
        {
            fileArray = valueproject["file"].toArray(); //取出file数组
            break;
        }

    }

    for(int i=0;i<fileArray.size();i++)
    {
        QJsonValue fileDetail = fileArray.at(i);
        QString fileDetailName = fileDetail["filename"].toString();
        if(fileDetailName == nowfile)
        {
            //识别到了目前的Json文件中的项目文件配置

            detail = fileDetail["detail"].toArray();
        }
    }

    if(fileModel!=nullptr)
    {
        fileModel->clear();
    }

    fileModel = new QStandardItemModel();
    fileModel->setHorizontalHeaderLabels(QStringList()<<QStringLiteral("名称")
                                         <<QStringLiteral("描述")<<QStringLiteral("长度")<<QStringLiteral("类型"));

    for(int i=0;i<detail.size();i++)
    {
        QJsonValue detailvalue = detail.at(i);
        QString name = detailvalue["name"].toString();
        QString desc = detailvalue["description"].toString();
        QString length = detailvalue["length"].toString();
        QString thiskind = detailvalue["type"].toString();
        int kind_index = 0;
        QComboBox *kind = new QComboBox;
        //实现：用户配置的参数类型先添加，用户没有选到的后添加，用户还能继续修改
        for(int i=0;i<type.length();i++)
        {
            if(type[i] == thiskind)
            {
                kind_index = i;
            }
        }
        kind->addItem(thiskind);
        for(int i=0;i<type.length();i++)
        {
            if(i == kind_index)
            {
                continue;
            }
            else
            {
                kind->addItem(type[i]);
            }
        }

        fileModel->setItem(i,0,new QStandardItem(name));
        fileModel->setItem(i,1,new QStandardItem(desc));
        fileModel->setItem(i,2,new QStandardItem(length));

        //fileModel->setItem(i,3,new QStandardItem(kind));
        ui->tableView_nowfile->setModel(fileModel);
        ui->tableView_nowfile->setIndexWidget(fileModel->index(i,3),kind);
    }

    if(detail.size()==0)
    {
        ui->tableView_nowfile->setModel(fileModel);
    }

}


void Ana::on_pushButton_addfile_clicked()
{


    if(ui->tableView_nowfile->model() == nullptr)
    {
        QMessageBox::warning(nullptr,"警告","请先创建或选择配置文件");
        return;
    }
    //先判断上一列的元素是否正常输入了
    QModelIndex index_name;
    int count = ui->tableView_nowfile->model()->rowCount();
    if(count!=0)
    {
        int lastrow = count - 1;
        index_name = fileModel->index(lastrow,0,QModelIndex());
        QModelIndex index_length = fileModel->index(lastrow,2,QModelIndex());
        QString name = index_name.data().toString();
        QString length = index_length.data().toString();
        if(name == ""||length==""||ifIsFullDigital(length)==false||ifIsFullDigital(name)==true)
        {
            QMessageBox::warning(nullptr,"警告","上一笔记录的域名或长度没有正常输入\n其中域名不能为空或纯数字\n长度不能为空且必须是整数");
            return;
        }
    }

    qDebug()<<count;

    QComboBox *filetype = new QComboBox;
    for(int i=0;i<type.length();i++)
    {
        filetype->addItem(type[i]);
    }

    QList<QStandardItem*> items1;
    fileModel->appendRow(items1);
    ui->tableView_nowfile->setModel(fileModel);

    ui->tableView_nowfile->setIndexWidget(fileModel->index(count,3),filetype);
    QModelIndex name = fileModel->index(count,0,QModelIndex());
    QWidget * focus = ui->tableView_nowfile->indexWidget(name);

    if(focus!=nullptr)
    {
        focus->setFocus();  //输入聚焦
    }
    ui->tableView_nowfile->repaint();
}


void Ana::on_pushButton_file_save_clicked()
{
    int count = 0;
    //下面实现保存Json文件
    if(ui->tableView_nowfile->model() == nullptr)
    {
        qDebug()<<"NULL";
        return;
    }
    else
    {
        count = ui->tableView_nowfile->model()->rowCount();
        qDebug()<<"目前页面的行数为："<<count;
    }
    //先判断上次输入是否正常
    if(iflastIsOk()==false)
    {
        QMessageBox::warning(nullptr,"警告","配置的名称或长度没有正常输入\n其中名称不能为空或纯数字\n长度不能为空且必须是整数");
        return;
    }
    QJsonArray thisfileDeatil;
    //index下标从0开始 长度-1
    for(int i=0;i<count;i++)
    {
        QModelIndex index_name = fileModel->index(i,0,QModelIndex());
        QModelIndex index_length = fileModel->index(i,2,QModelIndex());
        QModelIndex index_desc = fileModel->index(i,1,QModelIndex());
        QModelIndex index_type = fileModel->index(i,3,QModelIndex());  //这是个内嵌的QComboBox
        QString name = index_name.data().toString();
        QString length = index_length.data().toString();
        QString desc = index_desc.data().toString();
        QString type;
        QWidget *w = ui->tableView_nowfile->indexWidget(index_type);
        QComboBox *combo = dynamic_cast<QComboBox *>(w);
        type = combo->currentText();
        QJsonObject fileDetail{
            {"name",name },
            {"description",desc},
            {"length",length},
            {"type",type}
        };
        thisfileDeatil.append(fileDetail);
        //qDebug()<<Json2QString(fileDetail)<<"LINE = "<<__LINE__;
    }
    QJsonObject rootObject = readJsonfile2Object(myfilename); //主Json对象
    QJsonArray rootArray = readJsonObjectReturnArray(rootObject,"project"); //所有项目的数组
    QJsonArray fileArray; //对应项目文件数组
    QJsonArray detail; //对应文件配置数组 最小的一级
    QString name;
    QString desc;
    int indexproject = -1;
    for(int i=0;i<rootArray.size();i++)
    {
        QJsonValue valueproject = rootArray.at(i);
        if(valueproject["name"].toString() == ui->label_current_project->text())
        {
            fileArray = valueproject["file"].toArray(); //取出file数组
            indexproject = i;
            name = valueproject["name"].toString();
            desc = valueproject["description"].toString();
            break;
        }

    }
    if(indexproject == -1) //不该出现此情况
    {
        return;
    }
    QJsonObject newRoot;

    for(int i=0;i<fileArray.size();i++)
    {
        QJsonValue fileDetail = fileArray.at(i);
        QString fileDetailName = fileDetail["filename"].toString();
        if(fileDetailName == nowfilename)
        {
            //识别到了目前的Json文件中的项目文件配置
            QJsonObject thisfile{
                {"filename",fileDetail["filename"]},
                {"detail",thisfileDeatil}
            };
            fileArray[i] = thisfile;
            break;
        }
    }

    QJsonObject newproject{
        {"name",name},
        {"description",desc},
        {"file",fileArray}
    };

    rootArray[indexproject] = newproject;
    rootObject["project"] = rootArray;
    QFile file(myfilename);
    if(!file.open(QIODevice::WriteOnly))
    {
        return;
    }
    QJsonDocument jsondocu(rootObject);
    file.write(jsondocu.toJson());
    file.close();
    ui->tableView_nowfile->clearSpans();
    ui->stackedWidget->setCurrentIndex(0); //保存之后回到主窗口
}

bool Ana::iflastIsOk()//判断上一笔输入是否正常 后续要加上判断整个页面的输入
{
    int count = ui->tableView_nowfile->model()->rowCount();
    if(count!=0)
    {
        for(int i=0;i<count;i++)
        {
            int lastrow = i;
            QModelIndex index_name = fileModel->index(lastrow,0,QModelIndex());
            QModelIndex index_length = fileModel->index(lastrow,2,QModelIndex());
            QModelIndex index_type = fileModel->index(lastrow,3,QModelIndex());  //这是个内嵌的QComboBox
            QString name = index_name.data().toString();
            QString length = index_length.data().toString();
            QString type;
            QWidget *w = ui->tableView_nowfile->indexWidget(index_type);
            QComboBox *combo = dynamic_cast<QComboBox *>(w);
            type = combo->currentText();
            qDebug()<<type;
            if(name == ""||length==""||ifIsFullDigital(length)==false||ifIsFullDigital(name)==true)
            {

                return false;
            }
        }

        return true;

    }
    return false;

}

void Ana::on_PostSlov_clicked()
{
    if(flag == 1)
    {
        ui->stackedWidget->setCurrentIndex(3);
    }
    else
    {
        QMessageBox::warning(nullptr,"警告","请先创建或选择正确的项目配置");
    }
}


void Ana::on_pushButton_slov_clicked()
{

    post = ui->textEdit_post->toPlainText();
    ui->stackedWidget->setCurrentIndex(0);
    post_solve(post);
}

void Ana::post_solve(QString text)
{
    int solve_flag = 0;
    /*
     * QStringList name,desc,length,types;
     */
    int index = 0;
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);
    qDebug()<<"name = "<<name<<"desc"<<desc<<"length"<<length<<"types"<<types<<__LINE__;
    QStringList postList = QString(text).split(QRegExp("[\r\n]"),QString::SkipEmptyParts);

    QStringList result;
    for(int i=0;i<postList.length();i++) //报文有几行 就添加几行
    {
        index = 0; //每次读新行需要重置索引
        qDebug()<<"这一行数据为"<<text<<"长度为"<<text.length()<<__LINE__;
        ui->tableWidget->insertRow(i);
        int rowcount = name.length();
        for(int j=0;j<rowcount;j++)
        {
            int len = length[j].toInt();  //保存长度的数组数，也就代表了界面一共有几个列

            QString temp = postList[i].mid(index,len);
            //增加解析错误的处理
            qDebug()<<"types="<<types<<__LINE__;
            if(types[j] == "number"&&ifIsFullDigital(temp)==false)
            {
                temp += "(应为纯数字)";
                solve_flag++;
            }
            ui->tableWidget->setItem(i,j,new QTableWidgetItem(temp));
            index += len;
        }

        if(index != postList[i].length())
        {
            QString temp = "第"+QString::number(i+1)+"条报文的长度应为";
            result<<"报文解析出错:\n"<<temp<<QString::number(index)<<"\n实际长度为"<<QString::number(postList[i].length())<<"\n";
            if(solve_flag!=0)
            {
                result<<"其中"<<QString::number(solve_flag)<<"个域格式错误";
            }
        }

    }
    if(result.length()!=0)
    {

        QMessageBox::warning(nullptr,"警告",result.join(""));
    }
    ui->tableWidget->setEditTriggers(nullptr);

}


//本函数实现双击打开项目
void Ana::on_treeView_projectList_doubleClicked(const QModelIndex &index)
{
    QString selectedText = ui->treeView_projectList->model()->itemData(index).values()[0].toString();
    const QModelIndex currindex = ui->treeView_projectList->currentIndex();
    if(currindex.parent().isValid()==false) //说明点击了项目名
    {
        on_pushButton_changeProj_clicked();
    }
}



void Ana::on_FileSlov_clicked()
{
    int solve_flag = 0;
    if(flag == 1)
    {
        int index = 0;
        QString curPath=QDir::currentPath();//获取系统当前目录
        QString dlgTitle="打开一个文件"; //对话框标题
        QString filter="所有文件(*.*);;文本文件(*.txt);;程序文件(*.h *.cpp)"; //文件过滤器
        QString filename = QFileDialog::getOpenFileName(this,dlgTitle,curPath,filter);

        QFile file(filename);
        if(file.open(QIODevice::ReadOnly)==false)
        {
            QMessageBox::warning(nullptr,"警告","打开文件失败！");
            return;
        }
        QByteArray all = file.readAll();
        QString fileText;
        fileText.append(all);

        file.close();
        QStringList result;
        QStringList fileList = QString(fileText).split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
        for(int i=0;i<fileList.length();i++) //报文有几行 就添加几行
        {
            index = 0; //每次读新行需要重置索引

            ui->tableWidget->insertRow(i);
            int rowcount = name.length();
            for(int j=0;j<rowcount;j++)
            {
                int len = length[j].toInt();  //保存长度的数组数，也就代表了界面一共有几个列

                QString temp = fileList[i].mid(index,len);
                //增加解析错误的处理
                qDebug()<<"types="<<types<<__LINE__;
                if(types[j] == "number"&&ifIsFullDigital(temp)==false)
                {
                    temp += "(应为纯数字)";
                    solve_flag++;
                }
                ui->tableWidget->setItem(i,j,new QTableWidgetItem(temp));
                index += len;
            }
            if(index != fileList[i].length())
            {
                QString temp = "第"+QString::number(i+1)+"行文件的长度应为";
                result<<"文件解析出错:\n"<<temp<<QString::number(index)<<"\n实际长度为"<<QString::number(fileList[i].length())<<"\n";
                if(solve_flag!=0)
                {
                    result<<"其中"<<QString::number(solve_flag)<<"个域格式错误";
                }
            }

        }

        ui->tableWidget->setEditTriggers(nullptr);

    }
    else
    {
        QMessageBox::warning(nullptr,"警告","请先创建或选择正确的项目配置");
    }


}


//实现删除当前添加的内容
void Ana::on_pushButton_divfile_clicked()
{
    int row = ui->tableView_nowfile->currentIndex().row();
    QAbstractItemModel * model = ui->tableView_nowfile->model();
    QModelIndex index = model->index(row,0);
    QVariant data = model->data(index);
    QMessageBox::StandardButton result = QMessageBox::information(nullptr,"提示","确定要删除"+data.toString()+"吗？",QMessageBox::Yes|QMessageBox::No);
    if(result == QMessageBox::Yes)
    {
        fileModel->removeRow(row);
        ui->tableView_nowfile->setModel(fileModel);

    }
}

void Ana::on_pushButton_file_insert_clicked()
{
    int row = ui->tableView_nowfile->currentIndex().row();
    QComboBox *filetype = new QComboBox;
    for(int i=0;i<type.length();i++)
    {
        filetype->addItem(type[i]);
    }

    QList<QStandardItem*> items1;
    fileModel->insertRow(row,items1);
    ui->tableView_nowfile->setModel(fileModel);
    ui->tableView_nowfile->setIndexWidget(fileModel->index(row,3),filetype);
    ui->tableView_nowfile->repaint(); //不然看不到效果，鼠标点了才有用

}
